﻿using System;
using System.Text;
using System.Web;
using Yd.Model;
using Yd.CommCls;
using Yd.BLL;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.IO;

namespace Yd.HttpHandler
{
    public class Handler : HandlerBase
    {

        //string msg = "您的验证码是：{0}，请妥善保管好用户名和密码，以免泄漏！宽客真诚为您服务，如有问题联系客服微信号13738712039";

        public string LoginAdmin(HttpContext context)
        {
            string UserName = context.Request["UserName"].Trim();
            string PassWord = context.Request["PassWord"].Trim();
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord))
            {
                return GetResult("非法用户操作");
            }
            if (context.Request["yzm"].Trim().ToLower().Trim() != context.Session["CheckCodeb"].ToString().Trim().ToLower())
            {
                return GetResult("验证码错误");
            }
            SqlParameter[] fparam = new SqlParameter[] { 
                new SqlParameter("@UserName",UserName),
                new SqlParameter("@PassWord",CommUtils.GetMd5(PassWord))
            };
            DataSet ds = commdal.QueryObject("LoginAdmin", fparam);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                CommCls.CommUtils.WriteCookeLoginAdmin(ds.Tables[0].Rows[0]["aid"].ToString(), ds.Tables[0].Rows[0]["admin"].ToString());
                return GetResult("", "true");
            }
            return GetResult("用户名或密码错误");
        }

        public bool g()
        {
            DataSet ds = commdal.QueryObjectAllSql("select Id from tz_user where sfrz=1 and Id=" + CommCls.CommUtils.GetUserId());
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// The identity authentication  身份认证
        /// 获取身份认证状态
        /// </summary>
        /// <returns></returns>
        public string  getIA()
        {
            return getIA(CommCls.CommUtils.GetUserId());
        }
        public string getIA(string userid)
        {
            string ia = commdal.ExecuteScalarByCommand("select sfrz from tz_user where  Id=" + userid);
            return ia;
        }
        public string Login(HttpContext context)
        {
            string UserName = context.Request["UserName"].Trim();
            string PassWord = context.Request["PassWord"].Trim();
            string device = context.Request["device"];
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord))
            {
                return GetResult("非法用户操作");
            }
            if (context.Request["yzm"].Trim().ToLower().Trim() != context.Session["CheckCodeb"].ToString().Trim().ToLower())
            {
                return GetResult("验证码错误");
            }

            DataSet ds1 = commdal.QueryObjectAllSql("select * from tz_user where cwcs>=3 and cwsj>'" + DateTime.Now.AddMinutes(-30).ToString() + "' and username='" + UserName.Trim().Replace("\'", "") + "'");
            if (ds1 != null && ds1.Tables[0].Rows.Count > 0)
            {
                return GetResult("您输入的密码输错3次错误，请在30分钟之后再登陆!");
            }
            SqlParameter[] fparam = new SqlParameter[] { 
                new SqlParameter("@username",UserName),
                new SqlParameter("@userpwd",CommUtils.GetMd5(PassWord))
            };
            DataSet ds = commdal.QueryObject("LoginUser", fparam);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                //context.Session["Uid"] = ds.Tables[0].Rows[0]["Id"].ToString();
                //context.Session["Purview"] = ds.Tables[0].Rows[0]["Purview"].ToString();
                //context.Session["IsSuper"] = ds.Tables[0].Rows[0]["IsSuper"].ToString();
                //context.Session["UserName"] = ds.Tables[0].Rows[0]["IsSuper"].ToString().Trim();
                CommCls.CommUtils.WriteCookeLogin(ds.Tables[0].Rows[0]["Id"].ToString(), ds.Tables[0].Rows[0]["username"].ToString());
                commdal.SaveOrUpdateSql("update tz_user set cwcs=0 where username='" + UserName.Trim().Replace("\'", "") + "'");
                string insert = String.Format("INSERT INTO tz_login_log(uid,userName,device) VALUES({0},'{1}','{2}')", ds.Tables[0].Rows[0]["Id"].ToString(), ds.Tables[0].Rows[0]["username"].ToString(), device);
                commdal.SaveOrUpdateSql(insert);
                return GetResult("", "true");

            }
            else
            {
                commdal.SaveOrUpdateSql("update tz_user set cwcs=IsNull(cwcs,0)+1,cwsj=getdate() where username='" + UserName.Trim().Replace("\'","") + "'");
            }
            return GetResult("用户名,密码错误。或账号已注销");
        }

        public string NoHTML(string Htmlstring)
        {
            Htmlstring = Regex.Replace(Htmlstring, "<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(iexcl|#161);", "\x00a1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(cent|#162);", "\x00a2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(pound|#163);", "\x00a3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(copy|#169);", "\x00a9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Htmlstring.Replace("<", "");
            Htmlstring = Htmlstring.Replace(">", "");
            return Htmlstring;
        }
        public bool g1(string userId) {
            DataSet ds = commdal.QueryObjectAllSql("select Id from tz_user where IsStop=1 and Id=" + userId);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                return true;
            }
            return false;
        }
        public bool g1()
        {
            return g1(CommCls.CommUtils.GetUserId());
        }
        
        //验证手机端短信验证码是否正确
        public int GetdalVerifyCode(string mobile, string code, Int64 timeStamp)
        {
            string sql = String.Format("select timeStamp from tz_user_code where mobile='{0}' and code='{1}'", mobile, code);
            DataSet ds = commdal.QueryObjectAllSql(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                int dbTimeStamp = Convert.ToInt32(dr["timeStamp"]);
                if ((timeStamp - dbTimeStamp) > (30 * 60))
                {
                    return -6;//超时
                }
                else
                {
                    return 0;
                }
            }
            return -5;//验证码错误
        }

        public string modifgyss(HttpContext context)
        {
            string result = "";
            if (CommCls.CommUtils.GetUserId() == "0")
            {
                return GetResult("请先登录!");
            }
           
            string hyzk = context.Request["hyzk"].Trim();
            string province = context.Request["province"].Trim();
            string city = context.Request["city"].Trim();
            string address = NoHTML(context.Request["faddress"].Trim());
            string xl = context.Request["xl"].Trim();
            string hy = context.Request["hy"].Trim();
            string zw = context.Request["zw"].Trim();
            string sr = context.Request["sr"].Trim();
            int _fresult = commdal.SaveOrUpdateSql("update tz_user set hyzk='" + hyzk + "',province='" + province + "',city='" + city + "',address='" + address + "',xl='" + xl +
                "',hy='" + hy + "',zw='" + zw + "',sr='" + sr + "' where Id=" +
                CommCls.CommUtils.GetUserId());
            if (_fresult == 0)
            {
                result = GetResult("", "true");
            }
            else
            {
                result = GetResult("修改失败");
            }
            return result.Trim();
        }
        Random rnd = new Random();
        public override string Execute(HttpContext context)
        {
            string result = string.Empty;
            int _fresult = 0;
            yd_admin _admin = null;
            string _typename = context.Request["typename"].Trim();
            if (_typename.ToLower() == "lgnadmin")
            {
                return LoginAdmin(context);
            }
            if (_typename.ToLower() == "loginuser")
            {
                return Login(context);
            }
            try
            {
                switch (_typename.ToLower().Trim())
                {
                    case "scjt":
                        if (CommCls.CommUtils.GetUserIdA() == "0")
                        {
                            return GetResult("请先登录!");
                        }
                        DataSet dsscjt = commdal.QueryObjectAllSql("select Id from tz_news where fsid=1");
                        if (dsscjt != null && dsscjt.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dr in dsscjt.Tables[0].Rows)
                            {
                                CommCls.CommUtils.gethtml(dr["Id"].ToString().Trim());
                            }
                            int num = dsscjt.Tables[0].Rows.Count;
                            int _r = num % 10;
                            int _page = 0;//页数
                            if (_r == 0)
                            {
                                _page = (num / 10);
                            }
                            else
                                _page = (num / 10) + 1;
                            for (int ii = 1; ii <= _page; ii++)
                            {
                                CommCls.CommUtils.gethtmlPage(ii.ToString().Trim());
                            }
                        }
                        result=GetResult("操作成功!", "true");
                        break;
                    case "jinyongShop":
                        if (CommCls.CommUtils.GetUserIdA() == "0")
                        {
                            return GetResult("请先登录!");
                        }
                        commdal.SaveOrUpdateSql("update yd_shop set isForbidden=1 where suid=" + context.Request["Id"] + "");
                        result = GetResult("操作成功!", "true");
                        break;
                    case "jinyongUser":
                        if (CommCls.CommUtils.GetUserIdA() == "0")
                        {
                            return GetResult("请先登录!");
                        }
                        commdal.SaveOrUpdateSql("update yd_user set disabled=1 where uid=" + context.Request["Id"] + "");
                        result = GetResult("操作成功!", "true");
                        break;
                    case "sethot":
                        if (CommCls.CommUtils.GetUserIdA() == "0")
                        {
                            return GetResult("请先登录!");
                        }
                        commdal.SaveOrUpdateSql("update yd_shop set isRemen=1,sequence=" + context.Request["paixu"] + " where suid=" + context.Request["Id"]);
                        result = GetResult("操作成功!", "true");
                        break;
                    case "cancelhot":
                        if (CommCls.CommUtils.GetUserIdA() == "0")
                        {
                            return GetResult("请先登录!");
                        }
                        commdal.SaveOrUpdateSql("update yd_shop set isRemen=0,sequence=0 where suid=" + context.Request["Id"] + "");
                        result = GetResult("操作成功!", "true");
                        break;
                    case "delaction":
                        if (CommCls.CommUtils.GetUserIdA() == "0")
                        {
                            return GetResult("请先登录!");
                        }
                        commdal.SaveOrUpdateSql("update [dbo].[yd_action] set isDel=1 where hdId=" + context.Request["Id"] + "");
                        result = GetResult("操作成功!", "true");
                        break;
                    case "getmobnewslist": //手机端资金明细列表
                        int newpageindex = context.Request["page"].StrToInt();
                        string fsid = context.Request["fsid"];
                        DataSet newlist = commdal.QueryObjectAllSql("declare @t int Execute Proce_Sql_PageChange 'View_tz_news','*','Id desc','fsid=" + fsid + "',10," + newpageindex + ",@t output");
                        if (newlist != null && newlist.Tables[0].Rows.Count > 0)
                        {
                            StringBuilder listsb = new StringBuilder("[");
                            foreach (DataRow row in newlist.Tables[0].Rows)
                            {
                                listsb.Append("{");
                                listsb.AppendFormat("\"fadddate\":\"{0}\",", Convert.ToDateTime(row["fadddate"]).ToString("yyyy-MM-dd"));
                                listsb.AppendFormat("\"ftitle\":\"{0}\",", row["ftitle"].ToString());
                                listsb.AppendFormat("\"Id\":\"{0}\"", row["Id"].ToString());
                                listsb.Append("},");
                            }
                            listsb.Remove(listsb.ToString().LastIndexOf(','), 1);
                            listsb.Append("]");
                            result = GetResultJson(listsb.ToString(), "true");
                        }
                        else
                        {
                            result = GetResult("", "false");
                        }
                        break;
                }
            }
            catch (Exception e)
            {
                result = GetResult(e.Message);
            }
            return (result);
        }

        public string AddSort(HttpContext context)
        {
            SqlParameter[] fparam = new SqlParameter[] { 
                new SqlParameter("@SortName",context.Request["SortName"].Trim()),
                new SqlParameter("@SortParentId",context.Request["SortParentId"].StrToInt())
            };
            int _fresult = commdal.ExecuteStorePro("InsetHr_Sort", fparam);
            if (_fresult == -1)
            {
                return GetResult("当前类别名称已经存在");
            }
            return GetResult("", "true");
        }

        public string AddLj(HttpContext context)
        {
            SqlParameter[] fparam = new SqlParameter[] { 
                new SqlParameter("@LjKey",context.Request["LjKey"].Trim()),
                new SqlParameter("@LjUrl",context.Request["LjUrl"].Trim()),
                new SqlParameter("@LParentId",context.Request["LParentId"].StrToInt())
            };
            int _fresult = commdal.ExecuteStorePro("InsertHr_Lj", fparam);
            if (_fresult == -1)
            {
                return GetResult("当前链接名称已经存在");
            }
            return GetResult("", "true");
        }

        public string GetSort(string ParentId = "0")
        {
            DataSet ds = commdal.QuerySort(ParentId);
            StringBuilder _sb = new StringBuilder();
            _sb.Append("[");
            _sb.Append("{\"SortName\":\"第一级\",\"Id\":\"0\"}");
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["Id"].ToString() == "20" || ds.Tables[0].Rows[i]["Id"].ToString() == "30")
                    {
                        continue;
                    }
                    _sb.Append(",{\"SortName\":\"" + ds.Tables[0].Rows[i]["SortName"].ToString().Trim() + "\",\"Id\":\"" + ds.Tables[0].Rows[i]["Id"].ToString().Trim() + "\"}");
                }
            }
            return _sb.Append("]").ToString();
        }

        //public string getbankno(string bank)
        //{
        //    DataSet ds = commdal.QueryObjectAllSql("select clx from tz_bank where cardid='" + bank.Trim() + "'");
        //    if (ds != null && ds.Tables[0].Rows.Count > 0)
        //    {
        //        return bank + "(" + ds.Tables[0].Rows[0]["clx"].ToString().Trim() + ")";
        //    }
        //    return bank;
        //}
    }
}
